package ch.zbw.pra.sysventory.business.businessObject.scan;

import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

import ch.zbw.pra.sysventory.model.Processor;

/**
 * Gibt den Processor mittels WMI Schnittstelle auf einem bestimmten Host zurück
 * 
 * @author Ralph Koster
 */

public class ScanProcessorBusinessObject implements Serializable {

	private static final long serialVersionUID = 5482718017988178560L;
	private static Logger LOG = LoggerFactory.getLogger(ScanProcessorBusinessObject.class);
	
	private Processor cpu;

	
	public ScanProcessorBusinessObject() {
	
	}

	public Processor getProcessorFromHost(String host) {
		String connectStr = String.format("winmgmts:\\\\%s\\root\\CIMV2", host);
		String query = "SELECT * FROM Win32_Processor";

		try {
			ActiveXComponent axWMI = new ActiveXComponent(connectStr);
			Variant vCollection = axWMI.invoke("ExecQuery", new Variant(query));

			EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
			Dispatch item = null;
			while (enumVariant.hasMoreElements()) {
				item = enumVariant.nextElement().toDispatch();
				// Dispatch.call returns a Variant which we can convert to a java form.
				String processorName = Dispatch.call(item, "Name").toString();
				String processorFamily = Dispatch.call(item, "Family").toString();
				String procCores = Dispatch.call(item, "NumberOfCores").toString();
				String procClock = Dispatch.call(item, "MaxClockSpeed").toString();
				int processorCores = Integer.valueOf(procCores).intValue();
				int processorClock = Integer.valueOf(procClock).intValue();

				LOG.debug("Processor found: " + processorName + " Familie: " + processorFamily + " Cores: "
						+ processorCores + " Speed in MHz: " + processorClock);
				
				cpu = new Processor(processorName, processorFamily, processorCores, processorClock);

			}
		} catch (Exception e) {
			LOG.debug("Failed to load the processor from host" + host);
			LOG.error(e.toString());
		}
		return cpu;
	}
}
